﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Sinacor.UI.Application.Settings.SmartClient;
using System.Threading;
using Sinacor.UI.Application.Menu.SmartClient;
using Sinacor.Infra.UI.Session;
using Sinacor.Infra.UI.Authentication;
using Sinacor.Infra.Service.Data;
using System.Data.Common;
using System.Data;
using Sinacor.Infra.UI.Security.Licensing;
using Sinacor.Infra.UI.Controls.SmartClient;
using Sinacor.Infra.UI.Messaging;
using Sinacor.Infra.UI.Desktop.SmartClient;
using Sinacor.Infra.UI.Messaging.SmartClient;
using Sinacor.Infra.UI.Messaging.Internal;
using System.Reflection;
using System.Diagnostics;
using System.Configuration;
using System.IO;
using Sinacor.Infra.Common.Security.Cryptography;
namespace SinacorTester
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        ApplicationSettings _settings;
        MessageManager _messageManager;
        private const int DEFAULT_COMPANY_INDEX = 0;
        string fileName = "SinacorTesterUserConfiguration.txt";

        public Window1()
        {
            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            _settings = ApplicationSettings.GetInstance();
            _settings.BeginInit();

            Sinacor.Infra.UI.Session.ServerKeepAliveCommunication serverKeepAlive = new ServerKeepAliveCommunication();
            Sinacor.Infra.UI.Session.SessionManager.IServerKeepAlive = serverKeepAlive;

            LoadCompanies();

            SetDefaultValues();
        }

        private void SetDefaultValues()
        {
            if (File.Exists(fileName))
            {
                TextReader tw = new StreamReader(fileName);
                textBox1.Text = tw.ReadLine().Replace("USER=","");
                textBox2.Text = tw.ReadLine().Replace("PASSWORD=", "");
                comboBox1.SelectedValue = tw.ReadLine().Replace("COMPANYID=", "");
                
                tw.Close();
                tw = null;
            }
            
        }

        private void WriteDefaultValues()
        {
            if (File.Exists(fileName))
                File.Delete(fileName);

            TextWriter tw = new StreamWriter(fileName);
            tw.WriteLine("USER=" + textBox1.Text);
            tw.WriteLine("PASSWORD=" + textBox2.Text);
            tw.WriteLine("COMPANYID=" + comboBox1.SelectedValue.ToString());
            tw.Close();
            tw = null;
        }

        private void LoadCompanies()
        {
            List<Company> companies = new List<Company>();
            OracleDataBase db = new OracleDataBase();
            DbCommand cmd = db.GetSqlStringCommand("select cd_empresa,nm_empresa from tgeempr");

            using (IDataReader reader = db.ExecuteReader(cmd))
            {
                while (reader.Read())
                {
                    Company company = new Company();
                    company.Id = reader.GetValue<Int32>("cd_empresa");
                    company.Name = reader.GetValue<string>("nm_empresa");
                    companies.Add(company);
                }
            }

            comboBox1.SelectedValuePath = "Id";
            comboBox1.DisplayMemberPath = "Name";            
            comboBox1.ItemsSource = companies;

            comboBox1.SelectedIndex = DEFAULT_COMPANY_INDEX;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {

            SessionManager sm = SessionManager.GetInstance();

            User user = new User();
            user.LoginName = textBox1.Text;
            user.Password = RSACryptographer.EncryptString(textBox2.Text, Sinacor.Infra.Common.Security.Cryptography.RSACryptographer.PublicKey);

            sm.CreateSession(user, (Company)comboBox1.SelectedItem);

            try
            {
                LicensingManager _licensingManager = LicensingManager.GetInstance();

            }
            catch (Exception lcex)
            {
                // Se der problema ao carregar o licenciamento
                // Apresenta uma mensagem de erro ao usuário
                SinacorMessageBox.Show("Erro ao Logar! Verifique o usuário e a senha digitada!", SinacorMessageBoxButton.Ok, SinacorMessageBoxImage.Error);
                App.Current.Shutdown();
            }

            WriteDefaultValues();

            AlternativeMenu menu = new AlternativeMenu();
            menu.Show();
            this.Close();
        }
    }


}
